import {URL_BASE, URL_BASE_COURSE, URL_BASE_PAY} from './constants';
import request from './request';
import storage from '@/util/localStorage';
import axios from 'axios';
import LoadingUtil from '@/util/loading';
import Toast from 'react-native-tiny-toast';

const course_url = url => URL_BASE_COURSE + url;
const base_url = url => URL_BASE + url;
const pay_url = url => URL_BASE_PAY + url;

/**
 * 设备注册
 * @param params
 * @param cb
 * @returns {Promise<void>}
 */
export const req_login = async (params, cb) => {
    axios.defaults.baseURL = URL_BASE_COURSE;
    axios.defaults.headers.post['Content-Type'] = 'application/json';
    axios({
        method: 'post',
        url: '/coursesvc/auth/workout/registerDevice',
        data: params,
    }).then(function (response) {
        console.log('response ', response);
        const result = response.data;
        if (result.success === true) {
            const {deviceKey, deviceId, deviceGroup} = result;
            storage.storeData('TOKEN_INFO', {
                deviceKey: deviceKey,
                deviceId: deviceId,
                deviceGroup: deviceGroup,
                userName: params.username,
            });
            cb && cb();
        } else {
            LoadingUtil.dismissLoading();
            Toast.show('login failed', {
                position: Toast.position.CENTER,
            });
        }
    }).catch(err => {
        LoadingUtil.dismissLoading();
        Toast.show('login failed', {
            position: Toast.position.CENTER,
        });
    });
};

export const req_findClassesCategorie = params => request.get(course_url('/coursesvc/auth/workout/findClassesCategorie'), params);
export const req_courseCategory = categoryId => request.get(course_url(`/coursesvc/auth/workout/courseCategory/${categoryId}`), {});
export const req_course = courseId => request.get(course_url(`/coursesvc/auth/workout/course/${courseId}`), {});
export const req_execise = courseDetailId => request.get(course_url(`/coursesvc/auth/workout/execise/${courseDetailId}`), {});

export const checkUpdate = () => request.get('https://dev-course-svc.macvon.com/coursesvc/auth/device/checkUpdate', {});
